package com.inspur.gs.sbssdl.database.spqm.spqm.front.sbssryzs.voactions;
import com.inspur.edp.bff.api.manager.context.QueryContext;
import com.inspur.edp.bff.spi.action.query.AbstractQueryAction;
import com.inspur.edp.caf.db.dbaccess.DbParameter;
import com.inspur.edp.caf.db.dbaccess.DynamicResultRow;
import com.inspur.edp.caf.db.dbaccess.IConverToListFunc;
import com.inspur.edp.caf.db.dbaccess.IDbParameter;
import com.inspur.edp.cef.entity.condition.FilterCondition;
import com.inspur.edp.cef.entity.dependenceTemp.Pagination;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.entity.entity.IValuesContainer;
import com.inspur.edp.qdp.bql.api.IBqlExecuter;
import com.inspur.edp.qdp.bql.api.OptionType;
import io.iec.edp.caf.runtime.config.BqlBeanUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class queryDataVOAction extends AbstractQueryAction {

// select
private final String SELECT = " select gspuser.id as id,gspuser.code as user_code,gspuser.NAME_CHS as user_name,org.id as org_id,org.code as org_code,org.NAME_CHS as org_name ";
// from
private final String FROM = " from GSPUSER gspuser join GSPSYSORG org on org.id = gspuser.SYSORGID ";
// where
private String WHERE = " where org.STATE = 1";
// params
private final List<IDbParameter> params = new ArrayList<>();

private final IBqlExecuter bqlExecuter = BqlBeanUtil.getAppCtx().getBean(IBqlExecuter.class);


public queryDataVOAction(QueryContext context) {
	super(context);
}

@Override
public void execute() {
	// 获取前端的分页器、过滤器，观察前端F12中传递的JSON格式
	Pagination pageInfo = getQueryContext().getFilter().getPagination();
	ArrayList<FilterCondition> filters = getQueryContext().getFilter().getFilterConditions();

	// 查询数据
	ArrayList<IEntityData> rows = queryData(filters, pageInfo);
	// 查询数据总数
	Integer count = queryCount();
	pageInfo.setPageCount(rows.size());
	pageInfo.setTotalCount(count);

	// 通用的直接拷贝，将结果传递给下一个执行器
	HashMap<String, ArrayList<IEntityData>> queryresult = new HashMap<>();
	queryresult.put("queryresult", rows);
	getQueryContext().setQueryResult(rows);
	setResult(queryresult);

}


private ArrayList<IEntityData> queryData(ArrayList<FilterCondition> filters, Pagination pagination) {
	StringBuilder sql = new StringBuilder(SELECT + FROM);
	for (FilterCondition f : filters) {
		if (!f.getValue().isEmpty() && f.getFilterField().equals("user_name")) {
			WHERE += "and gspuser.NAME_CHS like '%' || :user_name || '%' ";
			params.add(new DbParameter("user_name", f.getValue()));
		}
		if (!f.getValue().isEmpty() && f.getFilterField().equals("user_code")) {
			WHERE += "and gspuser.code like '%' || :user_code || '%' ";
			params.add(new DbParameter("user_code", f.getValue()));
		}
		if (!f.getValue().isEmpty() && f.getFilterField().equals("org_id")) {
			WHERE += "and org.id = :org_id ";
			params.add(new DbParameter("org_id", f.getValue()));
		}
	}
	bqlExecuter.getOptions().setOptionType(OptionType.ExecuteSql);
	List<IEntityData> data = bqlExecuter.executeSelectStatement(appendPagination(sql, pagination), new ArrayList<>(), new myIconver(), params.toArray(new IDbParameter[]{}));
	return new ArrayList<>(data);
}

private String appendPagination(StringBuilder sql, Pagination pagination) {
	if (pagination == null) {
		pagination = new Pagination(20, 1);
	}
	int offset = pagination.getPageSize() * (pagination.getPageIndex() - 1);
	sql.append(WHERE)
			.append(" order by gspuser.ID ")
			.append(" offset ")
			.append(offset)
			.append(" rows FETCH NEXT ")
			.append(pagination.getPageSize())
			.append(" ROWS ONLY");
	return sql.toString();
}

// 调用sql查询总数
private Integer queryCount() {
	String sql = "select count(*) as count " + FROM + WHERE;
	bqlExecuter.getOptions().setOptionType(OptionType.ExecuteSql);
	List<DynamicResultRow> rows = bqlExecuter.executeSelectStatement(sql, new ArrayList<>(), params.toArray(new IDbParameter[]{}));
	for (DynamicResultRow row : rows) {
		if (row.get("count") != null) {
			return Integer.valueOf(row.get("count").toString());
		}
	}
	return 0;
}

// 查询到的结果，需要转换为IEntityData
private class myIconver implements IConverToListFunc<IEntityData> {
	private IEntityData vo;

	@Override
	public List<IEntityData> convert(List<DynamicResultRow> list) {
		// 将Vo中所有的字段都填入到这里
		ArrayList<IEntityData> entityData = new ArrayList<>();
		for (DynamicResultRow row : list) {
			vo = getContext().createData();
			for (String s : vo.getPropertyNames()) {
				if (vo.getValue(s) instanceof IValuesContainer) {

				} else {
					vo.setValue(s, row.get(s));
				}
			}
			entityData.add(vo);
		}
		return entityData;
	}

	private void setValue(DynamicResultRow row, String propertyName, String... vars) {
		((IValuesContainer) vo.getValue(propertyName)).setValue(propertyName, row.get(propertyName));
		for (String var : vars) {
			if (var != null) {
				String value = propertyName + "_" + var;
				((IValuesContainer) vo.getValue(propertyName)).setValue(value, row.get(value));
			}
		}
	}
}
}